package io.nutz.nutzsite.module.qn.controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.plugins.slog.annotation.Slog;

import io.nutz.nutzsite.common.base.Result;
import io.nutz.nutzsite.common.utils.ShiroUtils;
import io.nutz.nutzsite.module.exam.models.Question;
import io.nutz.nutzsite.module.exam.services.QuestionService;
import io.nutz.nutzsite.module.qn.models.Qnpaperdef;
import io.nutz.nutzsite.module.qn.models.Qnscores;
import io.nutz.nutzsite.module.qn.services.QnpaperdefService;
import io.nutz.nutzsite.module.qn.services.QnscoresService;
import io.nutz.nutzsite.module.sys.models.Mytask;
import io.nutz.nutzsite.module.sys.services.MytaskService;
import io.nutz.nutzsite.module.sys.services.UserService;
/**
 * 问卷结果 信息操作处理
 * 
 * @author lrw
 * @date 2020-07-26
 */
@IocBean
@At("/qn/scores")
public class QnscoresController {
	private static final Log log = Logs.get();

	@Inject
	private QnscoresService qnscoresService;
	@Inject
	private QnpaperdefService qnpaperdefService;
	@Inject
	private MytaskService mytaskService;
	@Inject
	private UserService userService;
	@Inject
	private QuestionService questionService;
	
	@RequiresPermissions("qn:scores:view")
	@At("")
	@Ok("th:/qn/scores/scores.html")
	public void index(HttpServletRequest req) {

	}

	/**
	 * 查询问卷结果列表
	 */
	@RequiresPermissions("qn:scores:list")
	@At
	@Ok("json")
	public Object list(@Param("pageNum")int pageNum,
					   @Param("pageSize")int pageSize,
					   @Param("name") String name,
					   @Param("beginTime") Date beginTime,
					   @Param("endTime") Date endTime,
					   @Param("orderByColumn") String orderByColumn,
					   @Param("isAsc") String isAsc,
					   HttpServletRequest req) {
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name)){
			//cnd.and("name", "like", "%" + name +"%");
		}
		if(Lang.isNotEmpty(beginTime)){
			cnd.and("create_time",">=", beginTime);
		}
		if(Lang.isNotEmpty(endTime)){
			cnd.and("create_time","<=", endTime);
		}
		return qnscoresService.tableList(pageNum,pageSize,cnd,orderByColumn,isAsc,null);
	}

	/**
	 * 新增问卷结果
	 */
	@At("/add")
	@Ok("th:/qn/scores/add.html")
	public void add( HttpServletRequest req) {

	}

	/**
	 * 新增保存问卷结果
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("qn:scores:add")
	@Slog(tag="问卷结果", after="新增保存问卷结果 id=${args[0].id}")
	public Object addDo(@Param("..") Qnscores scores,HttpServletRequest req) {
		try {
			qnscoresService.insert(scores);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 修改问卷结果
	 */
	@At("/edit/?")
	@Ok("th:/qn/scores/edit.html")
	public void edit(String id, HttpServletRequest req) {
		Qnscores scores = qnscoresService.fetch(id);
		req.setAttribute("scores",scores);
	}

    /**
     * 详情问卷结果
     */
    @At("/detail/?")
    @Ok("th:/qn/scores/detail.html")
    public void detail(String id, HttpServletRequest req) {
		Qnscores scores = qnscoresService.fetch(id);
        req.setAttribute("scores",scores);
    }

    /**
	 * 修改保存问卷结果
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("qn:scores:edit")
	@Slog(tag="问卷结果", after="修改保存问卷结果")
	public Object editDo(@Param("..") Qnscores scores,HttpServletRequest req) {
		try {
			if(Lang.isNotEmpty(scores)){

				qnscoresService.update(scores);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 删除问卷结果
	 */
	@At("/remove")
	@Ok("json")
	@RequiresPermissions("qn:scores:remove")
	@Slog(tag ="问卷结果", after= "删除问卷结果:${array2str(args[0])}")
	public Object remove(@Param("ids")String[] ids, HttpServletRequest req) {
		try {
			qnscoresService.delete(ids);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
//===========================================
	@At//
	@Ok("th:/qn/scores/qncount.html")
	public void viewbyti(@Param("ksid") String ksid,@Param("level") int level,
			HttpSession session,HttpServletRequest req){
		
		Qnpaperdef qnpub=qnpaperdefService.fetch(ksid);
		req.setAttribute("qnpub", qnpub);
		//List<Question> list =questionService.query(Cnd.where("kmid", "=", qnpub.getKmid()));
		//req.setAttribute("qntik", list);
		List<Object> array=new ArrayList<Object>();
		String sql="SELECT xy,zymc,bj,tiid,";
		sql+="sum(if(stuans='A',1,0)) as ctna,";
		sql+="sum(if(stuans='B',1,0)) as ctnb,";
		sql+="sum(if(stuans='C',1,0)) as ctnc,";
		sql+="sum(if(stuans='D',1,0)) as ctnd,";
		sql+="sum(if(stuans='E',1,0)) as ctne,";
		//sql+="sum(if(length(stuans)>1,1,0)) as ctnk ";
		sql+="GROUP_CONCAT(stuans separator '/') AS stuadv  ";
		sql+="from qnscores where ksid="+ksid;
		//User u=(User) session.getAttribute("me");
		//if(u.getRole().equals("3")) sql+=" and xy='"+u.getBj()+"'";
		switch(level){
		case 1:sql+=" group by tiid";break;//全校
		case 2:sql+=" group by xy,tiid";break;//学院
		case 3:sql+=" group by zymc,tiid";break;//专业
		case 4:sql+=" group by bj,tiid";break;//班级
		}
		sql+=" order by convert(xy using gbk),convert(zymc using gbk),convert(bj using gbk),tiid";
		Sql osql = Sqls.create(sql);
		osql.setCallback(new SqlCallback() {
	      public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
	      	List<Object> array0=new ArrayList<Object>();
	      	Map<String, Object> jsonobj;
	      	String stdstr="000";
	      	int newdepart=0;
	          while (rs.next()){
	          	jsonobj=new HashMap<String, Object>();
	          	String xy=rs.getString("xy");
	  			jsonobj.put("xy", xy);
	  			String zymc=rs.getString("zymc");
	  			jsonobj.put("zymc", zymc);
	  			String bj=rs.getString("bj");
	  			jsonobj.put("bj", bj);
	  			int qid=rs.getInt("tiid");
	  			jsonobj.put("tiid", qid);
	  			Question question =questionService.fetch(qid);
	  			jsonobj.put("question",question);
	  			int a=rs.getInt("ctna"),b=rs.getInt("ctnb"),c=rs.getInt("ctnc"),d=rs.getInt("ctnd"),e=rs.getInt("ctne");//,k=rs.getInt("ctnk");
	  			jsonobj.put("ctna", a);
	  			jsonobj.put("ctnb", b);
	  			jsonobj.put("ctnc", c);
	  			jsonobj.put("ctnd", d);
	  			jsonobj.put("ctne", e);
	  			int qtid=question.getQtid();
	  			if(qtid<5) jsonobj.put("stuadv", "");
	  			else jsonobj.put("stuadv", rs.getString("stuadv").replaceAll("/无/", "").replaceAll("/没有/", ""));
	  			//jsonobj.put("ctnk", k);
	  			jsonobj.put("actn", (a+b+c+d+e));//+k实际参加人数
	  			int num=0;//应参加人数
	  			switch(level){
	  	  		case 1:
	  	  			if(newdepart==0){
	  	  				num=mytaskService.count(Cnd.where("ksid", "=", ksid));
	  	  				newdepart=1;
	  	  			}
	  	  			break;//全校
/*	  	  		case 2:
	  	  			if(!xy.equals(stdstr)) {newdepart=0;stdstr=xy;}
	  	  			else {newdepart=1;break;}
	  	  			num=dao.count(User.class, Cnd.where("xy", "=", xy).and("bj", "in", bjs));break;//学院
	  	  		case 3:
	  	  			if(!zymc.equals(stdstr)) {newdepart=0;stdstr=zymc;}
	  	  			else {newdepart=1;break;}
	  	  			num=dao.count(User.class, Cnd.where("zymc", "=", zymc).and("bj", "in", bjs));break;//专业
	  	  		case 4:
	  	  			if(!bj.equals(stdstr)) {newdepart=0;stdstr=bj;}
	  	  			else {newdepart=1;break;}
	  	  			num=dao.count(User.class, Cnd.where("bj", "=", bj));break;//班级
*/	  	  		}
	  			jsonobj.put("toben", num);//
	  			array0.add(jsonobj);
	          }
	          return array0;
	      }
	  });
		qnscoresService.dao().execute(osql);
	  array=osql.getList(Object.class);
	  req.setAttribute("qnreport", array);
	}
}
